﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Configuration;
using System.Threading;

namespace MyShowsPlugin
{
    //class for making http requests (POST and GET) with cookies support
	public class HTTPClient
	{
		public static CookieCollection Cooks = new CookieCollection();

        private Encoding encoding = Encoding.UTF8;
		private string _proxy_server = null;
		private int _proxy_port = default(int);
		private string _proxy_user = null;
		private string _proxy_pass = null;

		public HTTPClient()
		{
		}

		public HTTPClient(string prx_server, int prx_port, string prx_user, string prx_pass)
		{
			this._proxy_server = prx_server;
			this._proxy_port = prx_port;
			this._proxy_user = prx_user;
			this._proxy_pass = prx_pass;
		}

		#region public void ClearCookie()
		public void ClearCookie()
		{
			lock (Cooks)
			{
				Cooks = new CookieCollection();
			}
		}
		#endregion

		#region Точки входа
		/// <summary>
		/// Метод GET
		/// </summary>
		/// <param name="path"></param>
		/// <returns></returns>
        public string PageGet(string path)
		{
            return PageGet(path, null);
		}

		/// <summary>
		/// Метод POST
		/// </summary>
		/// <param name="path"></param>
		/// <param name="postData"></param>
		/// <returns></returns>
        public string PageGet(string path, Dictionary<string, string> postData)
		{
			string result = null;
            try
            {
                HttpWebRequest httpWebRequest = HttpWebRequestGet(path);

                if (postData == null) //GET
                {
                    httpWebRequest.Method = "GET";
                }
                else //POST
                {
                    httpWebRequest.Method = "POST";
                    StringBuilder sbTemp = new StringBuilder();
                    foreach (KeyValuePair<string, string> item in postData)
                    {
                        if (sbTemp.Length > 0)
                            sbTemp.Append("&");

                        sbTemp.AppendFormat("{0}={1}", item.Key, item.Value);
                    }
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] byteQuery = encoding.GetBytes(sbTemp.ToString());
                    httpWebRequest.ContentLength = byteQuery.Length;
                    using (Stream queryStream = httpWebRequest.GetRequestStream())
                    {
                        queryStream.Write(byteQuery, 0, byteQuery.Length);
                        queryStream.Close();
                    }
                }

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (httpWebResponse.StatusCode.ToString() != "OK")
                {
                    result = httpWebResponse.StatusCode.ToString();
                }
                httpWebResponse.Cookies = httpWebRequest.CookieContainer.GetCookies(httpWebRequest.RequestUri);
                if (httpWebResponse.Cookies != null)
                {
                    lock (Cooks)
                    {
                        Cooks.Add(httpWebResponse.Cookies);
                    }
                }

                using (StreamReader reader1 = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("windows-1251")))
                {
                    result = reader1.ReadToEnd();
                    reader1.Close();
                }
            }
            catch (Exception ex)
            {
                result = string.Format("ERROR:{0}", ex.Message);
            }

			return result;
		}
		#endregion

		#region private HttpWebRequest HttpWebRequestGet(string url)
		private HttpWebRequest HttpWebRequestGet(string url)
		{
			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

			if (!string.IsNullOrEmpty(this._proxy_server))
			{
				req.Proxy = new WebProxy(this._proxy_server, this._proxy_port);

				if (!string.IsNullOrEmpty(this._proxy_user))
				{
					req.Proxy.Credentials = new NetworkCredential(this._proxy_user, this._proxy_pass);
				}

			}

			req.AllowAutoRedirect = false;
			//req.Timeout = 60000;
			req.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)";

			req.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
			req.Referer = url;
			//req.Referer = @"http://" + url;

			req.CookieContainer = new CookieContainer();
			if (Cooks != null)
				req.CookieContainer.Add(Cooks);

			return req;
		}
		#endregion
	}

}
